#coding= utf-8
#20170906 目前存在一些BUG 没有方块被移动也有新数字出现。
import sys
from PyQt5 import QtGui,QtCore
import datetime
import random
import sip

class ExtendedQLabel(QtGui.QLabel):
    def __init(self, parent):
        QtGui.QLabel.__init__(self, parent)

    def mouseReleaseEvent(self, ev):
        self.emit(QtCore.SIGNAL('clicked(PyQt_PyObject)'), self)

class Blocked():
    def __init__(self):
        self.num = random.randrange(0, 6, 2)
        self.color = colors(self.num)

    def colors(self,num):
        if num == 0:
            return "NavajoWhite"
        elif num == 2:
            return "Goldenrod"
        elif num == 4:
            return "Sienna"
        elif num == 8:
            return "Brown"
        elif num == 16:
            return "Plum"
        elif num == 32:
            return "RoyalBlue"
        elif num == 64:
            return  "YellowGreen"
        elif num == 128:
            return "BlueViolet"
        elif num == 256:
            return "LightGreen"
        elif num == 512:
            return "SlateBlue"
        elif num == 1024:
            return "SpringGreen"
        elif num == 2048:
            return "HotPink"
        elif num == 4096:
            return "LightSkyBlue"
        else:
            return "White"

class MainWindow(QtGui.QMainWindow):

    def __init__(self , parent = None):
        super(MainWindow, self).__init__( parent)
        self.list = [[random.randrange(0, 6, 2) for col in range(4)] for row in range(4)]
        self.score = 0
        self.timess = datetime.datetime.now().second
        self.setWindowTitle("geme_test")
        self.setFixedSize(400, 400)
        self.init()

    def colors(self,num):
        if num == 0:
            return "NavajoWhite"
        elif num == 2:
            return "Goldenrod"
        elif num == 4:
            return "Sienna"
        elif num == 8:
            return "Brown"
        elif num == 16:
            return "Plum"
        elif num == 32:
            return "RoyalBlue"
        elif num == 64:
            return  "YellowGreen"
        elif num == 128:
            return "BlueViolet"
        elif num == 256:
            return "LightGreen"
        elif num == 512:
            return "SlateBlue"
        elif num == 1024:
            return "SpringGreen"
        elif num == 2048:
            return "HotPink"
        elif num == 4096:
            return "LightSkyBlue"
        else:
            return "White"

    def del_blk(self, lst):
        for i in lst:
            if i == 0:
                lst.remove(i)
                lst.append(0)
        return lst

    def merge(self, lst):
        lst = self.del_blk(lst)
        lst_tmp = []
        if len(lst) < 2:
            return lst
        else:
            if lst[0] == lst[1]:
                lst[0] += lst[1]
                self.score += lst[0]
                lst.pop(1)
                lst.append(0)
            lst_tmp.append(lst[0])
            lst.pop(0)
            lst_tmp += self.merge(lst)
        return lst_tmp

    def radom_num(self, lst):
        key = []
        for i in range(4):
            for j in range(4):
                if lst[i][j] == 0:
                    key.append([i, j])
        if key == []:
            print("Game Over!")
            sys.exit(0)
        key1 = random.choice(key)
        lst[key1[0]][key1[1]] = random.choice([2, 4])
        return lst

    def keyReleaseEvent(self, e):
        if e.key() == QtCore.Qt.Key_W:
            self.judgekey(self.list,"U")
        elif e.key() == QtCore.Qt.Key_S:
            self.judgekey(self.list,"D")
        elif e.key() == QtCore.Qt.Key_A:
            self.judgekey(self.list, "L")
        elif e.key() == QtCore.Qt.Key_D:
            self.judgekey(self.list, "R")

    def judgekey(self, lst, dirc):
        if dirc == 'L' or dirc == 'l':
            for i in range(4):
                lst[i] = self.merge(lst[i])
        elif dirc == 'R' or dirc == 'r':
            for i in range(4):
                lst[i] = lst[i][::-1]
                lst[i] = self.merge(lst[i])
                lst[i] = lst[i][::-1]
        elif dirc == 'U' or dirc == 'u':
            lst_tmp = [[0 for i in range(4)] for j in range(4)]
            for i in range(4):
                lst_tmp[i] = [x[i] for x in lst]
                lst_tmp[i] = self.merge(lst_tmp[i])
            for i in range(4):
                lst[i] = [x[i] for x in lst_tmp]
        elif dirc == 'D' or dirc == 'd':
            lst_tmp = [[0 for i in range(4)] for j in range(4)]
            for i in range(4):
                lst_tmp[i] = [x[i] for x in lst]
                lst_tmp[i] = lst_tmp[i][::-1]
                lst_tmp[i] = self.merge(lst_tmp[i])
                lst_tmp[i] = lst_tmp[i][::-1]
            for i in range(4):
                lst[i] = [x[i] for x in lst_tmp]
        elif dirc == 'e':
            sys.exit(0)
        lst = self.radom_num(lst)
        self.change_lable(lst)

    def init(self):
        self.layout = QtGui.QGridLayout()
        self.widget = QtGui.QWidget(self)
        self.widget.setLayout(self.layout)
        self.setCentralWidget(self.widget)
        self.tim = QtCore.QTimer(self)
        self.num = 0
        # self.tim.timeout.connect(self.init_lable)
        # self.tim.start(200)
        self.init_lable(self.list)
        self.change_lable(self.list)

    def change_lable(self,lst):
        num = 0
        for i in range(0, 4):
            for j in range(0, 4):
                lable = vars(self)["lable_%d" %num]
                lable.setStyleSheet(
                    'background-color: %s;'
                    'color: rgb(0, 0,0);'
                    'font: 75 25pt "Axure Handwriting";'%(self.colors(lst[i][j]))
                )
                lable.setAlignment(QtCore.Qt.AlignCenter)
                lable.setText(str(lst[i][j]))
                num += 1

    def init_lable(self,lst):
        num = 0
        for i in range(0, 4):
            for j in range(0, 4):
                lable = ExtendedQLabel()
                vars(self)["lable_%d" % num] = lable
                lable.setStyleSheet(
                    'background-color: #FFFAFA;'
                    'color: rgb(0, 170, 50);'
                    'font: 75 25pt "Axure Handwriting";'
                )
                lable.setAlignment(QtCore.Qt.AlignCenter)
                lable.setText(str(lst[i][j]))
                self.layout.addWidget(lable, i + 1, j)
                self.connect(lable, QtCore.SIGNAL("clicked(PyQt_PyObject)"), self.change_lable)
                num += 1


def startGame():
    app = QtGui.QApplication(sys.argv)
    Window = MainWindow()#这里提示Window没有使用？但如果不使用if __name__ == '__main__':怎不会提示
    Window.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    startGame()#将startGame()在这里展开会引起关闭程序是崩溃

